package cn.bitkit.component.common;

import cn.bitkit.base.constants.BasicApiCode;
import cn.bitkit.base.container.ApiResponse;
import cn.bitkit.base.exception.BusinessException;
import cn.bitkit.base.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ApiDataHandler {

    public static <S> S getData(ApiResponse<S> response){
        if(response == null){
            throw new BusinessException("服务请求失败");
        }
        if(ApiResponse.isFail(response)){
            throw new BusinessException(response.getMsg());
        }
        return response.getData();
    }

    public static <S> S getAndCheckData(ApiResponse<S> response){
        if(response == null){
            throw new BusinessException("服务请求失败");
        }
        if(ApiResponse.isFail(response)){
            throw new BusinessException(response.getMsg());
        }
        if(response.getData() == null){
            throw new BusinessException("服务返回数据为空");
        }
        return response.getData();
    }

    public static void initException(Exception e, ApiResponse<?> response){
        if(e instanceof BusinessException be){
            response.setCode(be.getErrorCode());
            response.setMsg(getErrorMsg(be.getErrorMsg()));
            return;
        }
        response.setCode(BasicApiCode.FAIL.code);
        response.setMsg(BasicApiCode.FAIL.desc);
    }

    public static String getErrorMsg(String msg) {
        if(StringUtil.isEmpty(msg)) {
            return BasicApiCode.FAIL.desc;
        }
        if(msg.toLowerCase().contains("exception")) {
            return BasicApiCode.FAIL.desc;
        }
        return msg;
    }

}
